package com.example.wasaimovie.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.wasaimovie.Model.support.ResponseResult;
import com.example.wasaimovie.Util.JwtTokenUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        response.setContentType("application/json;charset=utf8");
        response.setCharacterEncoding("utf-8");
        System.out.println(request.getRequestURI());
        ResponseResult<Object> obj = new ResponseResult<>();
        if ("options".equalsIgnoreCase(request.getMethod())){
            return true;
        }
        if (token == null || "".equals(token) || token.length() == 0 || "null".equalsIgnoreCase(token) || "undefined".equalsIgnoreCase(token)){
            // 不存在token
            PrintWriter out = response.getWriter();
            obj.setCode(404);
            System.out.println("token:" + token);
            obj.setMsg("用户未登录");
            JSONObject json = (JSONObject) JSONObject.toJSON(obj);
            // SerializerFeature.WRITE_MAP_NULL_FEATURES json保留null值
            // SerializerFeature.QuoteFieldNames 输出key时加上双引号
            String result = JSON.toJSONString(json, SerializerFeature.WRITE_MAP_NULL_FEATURES,
                    SerializerFeature.QuoteFieldNames);
            out.write(result);
            out.flush();
            out.close();
            return false;
        } else {
            // token 存在，验证是否过期
            if (JwtTokenUtil.isExpiration(token)){
                // token 过期
                PrintWriter out = response.getWriter();
                obj.setCode(404);
                obj.setMsg("登录信息已过期");
                JSONObject json = (JSONObject) JSONObject.toJSON(obj);
                // SerializerFeature.WRITE_MAP_NULL_FEATURES json保留null值
                // SerializerFeature.QuoteFieldNames 输出key时加上双引号
                String result = JSON.toJSONString(json, SerializerFeature.WRITE_MAP_NULL_FEATURES,
                        SerializerFeature.QuoteFieldNames);
                out.write(result);
                out.flush();
                out.close();
                System.out.println("token验证未通过,请重新登陆");
                return false;
            } else {
                // token未过期,验证是否访问管理员页面
                String url = request.getRequestURI();
                if (url.indexOf("/admin") >= 0){
                    // 访问管理员页面，需要验证管理员权限
                    List<String> roles = JwtTokenUtil.getTokenRoles(token);
                    boolean isAdmin = false;
                    for (String role : roles) {
                        if (role.equalsIgnoreCase("admin")){
                            // 是管理员
                            isAdmin = true;
                            break;
                        }
                    }
                    if (isAdmin){
                        return true;
                    } else {
                        PrintWriter out = response.getWriter();
                        obj.setCode(404);
                        obj.setMsg("非用户界面，禁止访问");
                        JSONObject json = (JSONObject) JSONObject.toJSON(obj);
                        // SerializerFeature.WRITE_MAP_NULL_FEATURES json保留null值
                        // SerializerFeature.QuoteFieldNames 输出key时加上双引号
                        String result = JSON.toJSONString(json, SerializerFeature.WRITE_MAP_NULL_FEATURES,
                                SerializerFeature.QuoteFieldNames);
                        out.write(result);
                        out.flush();
                        out.close();
                        System.out.println("token验证未通过");
                        return false;
                    }
                }
                return true;
            }
        }
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//    }
}
